//
// Created on 2025/7/2.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".
// 生产者-消费者模型实现 

#include "ProducerConsumer.h"


void ProducerConsumerQueue::PutElement(string element) {
    unique_lock<mutex> lock(m_mutex); // add mutex


    while (isFull()) {
        // when the data buffer queue is full, the production is blocked and wakes up after consumer consumption
        // m_mutex is automatically released at the same time
        m_notFull.wait(lock);
    }
    // reacquire the lock
    // if the queue is not full
    // the product is added to the queue and the consumer is notified that the product can be consumed
    m_queue.push(element);
    m_notEmpty.notify_one();
}
string ProducerConsumerQueue::TakeElement() {
    unique_lock<mutex> lock(m_mutex); // add mutex


    while (isEmpty()) {
        // when the data buffer queue is empty, the consumption is blocked and the producer is woken up after production
        // m_mutex is automatically released at the same time
        m_notEmpty.wait(lock);
    }
    // reacquire the lock
    // if the queue is not empty, the product is ejected and the producer is notified that it is ready for production
    string element = m_queue.front();
    m_queue.pop();
    m_notFull.notify_one();
    return element;
}

